package com.whty.system.util;



import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;

/**
 * 通用工具类,封装了很多常用方法
 */
public class CommonMethods {
    private static final String TAG = "CommonMethods";
    /*DISPLAY_WIDTH = 100 */
    final static float DISPLAY_WIDTH = 100;
    /*DISPLAY_HEIGHT = 160 */
    final static float DISPLAY_HEIGHT = 160;

    /**
     * byte字节数组转换Short类型（未严格测试）
     *
     * @param outBuf
     * @return
     */
    public static short bytesToShort(byte[] outBuf) {

        if (outBuf.length < 2) {
            return (short) (outBuf[0] < 0 ? outBuf[0] + 256 : outBuf[0]);
        } else {
            return (short) (((outBuf[0] < 0 ? outBuf[0] + 256 : outBuf[0]) << 8) + (outBuf[1] < 0 ? outBuf[1] + 256
                    : outBuf[1]));
        }

    }

    /**
     * @param str       原始字符串
     * @param len       目标长度
     * @param padding   填充内容
     * @param direction 填充方向： 0 左边，1 右边
     * @return
     */
    public static String PaddingStr(String str, int len, String padding,
                                    int direction) {
        String result = str;
        int r_len = result.length();
        if (r_len > len) {
            return result.substring(r_len - len, r_len);
        }
        if (r_len == len) {
            return result;
        }
        StringBuffer strBuff = new StringBuffer(result);
        if (direction == 0) {// 左边填充
            for (int i = 0; i < len - r_len; i++) {
                strBuff.insert(0, padding);
            }
        } else {// 右边填充
            for (int i = 0; i < len - r_len; i++) {
                strBuff.append(padding);
            }
        }
        return strBuff.toString();
    }

    /**
     * 填充XX数据，如果结果数据块是8的倍数，不再进行追加,如果不是,追加0xXX到数据块的右边，直到数据块的长度是8的倍数。
     *
     * @param data 待填充XX的数据
     * @return
     */
    public static String padding(String data, String inData) {
        int padlen = 8 - (data.length() / 2) % 8;
        if (padlen != 8) {
            String padstr = "";
            for (int i = 0; i < padlen; i++)
                padstr += inData;
            data += padstr;
            return data;
        } else {
            return data;
        }
    }

    /**
     * 填充80数据，首先在数据块的右边追加一个
     * '80',如果结果数据块是8的倍数，不再进行追加,如果不是,追加0x00到数据块的右边，直到数据块的长度是8的倍数。
     *
     * @param data 待填充80的数据
     * @return
     */
    public static String padding80(String data) {
        int padlen = 8 - (data.length() / 2) % 8;
        String padstr = "";
        for (int i = 0; i < padlen - 1; i++)
            padstr += "00";
        data = data + "80" + padstr;
        return data;
    }

    /**
     * 生成指定长度的动态链接库鉴权十六进制随机数字符串
     *
     * @return String
     */
    public static String yieldHexRand(int len) {
        StringBuffer strBufHexRand = new StringBuffer();
        Random rand = new Random(System.currentTimeMillis());
        int index;
        // 随机数字符
        char charArrayHexNum[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9',
                '0', 'A', 'B', 'C', 'D', 'E', 'F'};
        for (int i = 0; i < len; i++) {
            index = Math.abs(rand.nextInt()) % 16;
            if (i == 0) {
                while (charArrayHexNum[index] == '0') {
                    index = Math.abs(rand.nextInt()) % 16;
                }
            }
            strBufHexRand.append(charArrayHexNum[index]);
        }
        return strBufHexRand.toString();
    }

    /**
     * 生成随机String,length长度
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "0123456789abcdef";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 分析类名
     *
     * @param strName String
     * @return String
     */
    public static String analyseClassName(String strName) {
        String strTemp = strName.substring(strName.lastIndexOf(".") + 1,
                strName.length());
        return strTemp.substring(strTemp.indexOf(" ") + 1, strTemp.length());
    }

    static public String convertInt2String(int n, int len) {
        String str = String.valueOf(n);
        int strLen = str.length();

        String zeros = "";
        for (int loop = len - strLen; loop > 0; loop--) {
            zeros += "0";
        }

        if (n >= 0) {
            return zeros + str;
        } else {
            return "-" + zeros + str.substring(1);
        }
    }

    public static int convertString2Int(String str, int defaultValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static String getMonthLastDay(String year, String month) {
        String lastday = "";
        int y = Integer.parseInt(year);
        int m = Integer.parseInt(month);
        if (m == 2) {
            if (y % 4 == 0) {
                lastday = year + month + "29";
            } else {
                lastday = year + month + "28";
            }

        } else {
            if ((m <= 7 && m % 2 != 0) || (m > 7 && m % 2 == 0)) {
                lastday = year + month + "31";
            } else {
                lastday = year + month + "30";
            }
        }
        return lastday;
    }

    /**
     * yyMMdd
     */
    public static String getDate() {
        Calendar cal = Calendar.getInstance();
        return new SimpleDateFormat("yyMMdd").format(cal.getTime());
    }

    /**
     * yyyyMMdd
     */
    public static String getDateNow() {
        SimpleDateFormat dff = new SimpleDateFormat("yyyyMMdd");
        dff.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        return dff.format(new Date());
    }

    /**
     * yyyyMMddhhmmss
     */
    public static String getDateTime() {
        Calendar cal = Calendar.getInstance();
        return new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss").format(cal.getTime());

    }

    /**
     * hhmmss
     */
    public static String getTime() {
        Calendar cal = Calendar.getInstance();
        return new SimpleDateFormat("hhmmss").format(cal.getTime());
    }


    /**
     * 字符串日期转为yy-MM-dd HH:mm:ss格式
     *
     * @param dateStr
     * @return
     */
    public static String strToDateFormat(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
            Date date = sdf.parse(dateStr);
            SimpleDateFormat sf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
            String dateF = sf.format(date);
            return dateF;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字符串日期转为yyyy-MM-dd HH:mm:ss格式
     *
     * @param dateStr
     * @return
     */
    public static String strToDate(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = null;
            try {
                date = sdf.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String dateF = sf.format(date);
            return dateF;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字符串日期转为yyyy-MM-dd HH:mm:ss格式
     *
     * @param dateStr
     * @return
     */
    public static String strToDate2(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = null;
            try {
                date = sdf.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateF = sf.format(date);
            return dateF;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String bytesToHexString(byte[] bytes) {
        if (bytes == null) {
            return "";
        }
        StringBuffer buff = new StringBuffer();
        int len = bytes.length;
        for (int j = 0; j < len; j++) {
            if ((bytes[j] & 0xff) < 16) {
                buff.append('0');
            }
            buff.append(Integer.toHexString(bytes[j] & 0xff));
        }
        return buff.toString();
    }

    /**
     * usage: str2bytes("0710BE8716FB"); it will return a byte array, just like
     * : b[0]=0x07;b[1]=0x10;...b[5]=0xfb;
     */
    public static byte[] str2bytes(String src) {
        if (src == null || src.length() == 0 || src.length() % 2 != 0) {
            return null;
        }
        int nSrcLen = src.length();
        byte byteArrayResult[] = new byte[nSrcLen / 2];
        StringBuffer strBufTemp = new StringBuffer(src);
        String strTemp;
        int i = 0;
        while (i < strBufTemp.length() - 1) {
            strTemp = src.substring(i, i + 2);
            byteArrayResult[i / 2] = (byte) Integer.parseInt(strTemp, 16);
            i += 2;
        }
        return byteArrayResult;
    }

    public static int strcpy(byte d[], byte s[], int from, int maxlen) {
        int i;
        for (i = 0; i < maxlen; i++) {
            d[i + from] = s[i];
        }

        d[i + from] = 0;
        return i;
    }

    public static int memcpy(byte d[], byte s[], int from, int maxlen) {
        int i;
        for (i = 0; i < maxlen; i++) {
            d[i + from] = s[i];
        }
        return i;
    }

    public static void BytesCopy(byte[] dest, byte[] source, int offset1,
                                 int offset2, int len) {
        for (int i = 0; i < len; i++) {
            dest[offset1 + i] = source[offset2 + i];
        }
    }

    /**
     * usage: input: n = 1000000000 ( n = 0x3B9ACA00) output: byte[0]:3b
     * byte[1]:9a byte[2]:ca byte[3]:00 notice: the scope of input integer is [
     * -2^32, 2^32-1] ; **In CMPP2.0,the typeof msg id is ULONG,so,need
     * ulong2Bytes***
     */
    public static byte[] int2Bytes(int n) {
        ByteBuffer bb = ByteBuffer.allocate(4);
        bb.putInt(n);
        return bb.array();
    }

    public static byte[] long2Bytes(long l) {
        ByteBuffer bb = ByteBuffer.allocate(8);
        bb.putLong(l);
        return bb.array();
    }

    /**
     * 将整数转为16进行数后并以指定长度返回（当实际长度大于指定长度时只返回从末位开始指定长度的值）
     *
     * @param val int 待转换整数
     * @param len int 指定长度
     * @return String
     */
    public static String Int2HexStr(int val, int len) {
        String result = Integer.toHexString(val).toUpperCase();
        int r_len = result.length();
        if (r_len > len) {
            return result.substring(r_len - len, r_len);
        }
        if (r_len == len) {
            return result;
        }
        StringBuffer strBuff = new StringBuffer(result);
        for (int i = 0; i < len - r_len; i++) {
            strBuff.insert(0, '0');
        }
        return strBuff.toString();
    }

    public static String Long2HexStr(long val, int len) {
        String result = Long.toHexString(val).toUpperCase();
        int r_len = result.length();
        if (r_len > len) {
            return result.substring(r_len - len, r_len);
        }
        if (r_len == len) {
            return result;
        }
        StringBuffer strBuff = new StringBuffer(result);
        for (int i = 0; i < len - r_len; i++) {
            strBuff.insert(0, '0');
        }
        return strBuff.toString();
    }


    /**
     * 字符串转换为字节数组
     * <p>
     * stringToBytes("0710BE8716FB"); return: b[0]=0x07;b[1]=0x10;...b[5]=0xfb;
     */
    public static byte[] stringToBytes(String string) {
        if (string == null || string.length() == 0 || string.length() % 2 != 0) {
            return null;
        }
        int stringLen = string.length();
        byte byteArrayResult[] = new byte[stringLen / 2];
        StringBuffer sb = new StringBuffer(string);
        String strTemp;
        int i = 0;
        while (i < sb.length() - 1) {
            strTemp = string.substring(i, i + 2);
            byteArrayResult[i / 2] = (byte) Integer.parseInt(strTemp, 16);
            i += 2;
        }
        return byteArrayResult;
    }

    /**
     * 字节数组转为16进制
     *
     * @param bytes 字节数组
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        if (bytes == null) {
            return "";
        }
        StringBuffer buff = new StringBuffer();
        int len = bytes.length;
        for (int j = 0; j < len; j++) {
            if ((bytes[j] & 0xff) < 16) {
                buff.append('0');
            }
            buff.append(Integer.toHexString(bytes[j] & 0xff));
        }
        return buff.toString();
    }

    /**
     *
     * ********************************************************************<br>
     * 方法功能：将用户圈存金额先转换为分，在把分转为16进制，再前补0组装为4字节圈存金额 如1元 为:"00000064" 参数说明：<br>
     * 作 者：杨明<br>
     * 开发日期：2013-9-18 上午11:53:56<br>
     * 修改日期：<br>
     * 修改人：<br>
     * 修改说明：<br>
     * ********************************************************************<br>
     */
    /**
     * 将长整数转为16进行数后并以指定长度返回（当实际长度大于指定长度时只返回从末位开始指定长度的值）
     *
     * @param val int 待转换长整数
     * @param len int 指定长度
     * @return String
     */
    public static String longToHex(long val, int len) {
        String result = Long.toHexString(val).toUpperCase();
        int rLen = result.length();
        if (rLen > len) {
            return result.substring(rLen - len, rLen);
        }
        if (rLen == len) {
            return result;
        }
        StringBuffer strBuff = new StringBuffer(result);
        for (int i = 0; i < len - rLen; i++) {
            strBuff.insert(0, '0');
        }
        return strBuff.toString();
    }

    public static String moneyHexToDouble(String hexMoney) {
        int balance = -1;
        double balanceDouble = 0.0;
        if (hexMoney != null) {
            balance = Integer.parseInt(hexMoney, 16);
            balanceDouble = (double) balance / 100;
        }
        return balanceDouble + "";
    }

    /**
     * author：赵文星
     * 生成8个字节随机数
     *
     * @return
     */
    public static String getRand16() {
        StringBuffer strBufHexRand = new StringBuffer();
        Random rand = new Random(System.currentTimeMillis());
        int index;
        // 随机数字符
        char charArrayHexNum[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9',
                '0'};
        for (int i = 0; i < 16; i++) {
            index = Math.abs(rand.nextInt()) % 10;
            if (i == 0) {
                while (charArrayHexNum[index] == '0') {
                    index = Math.abs(rand.nextInt()) % 10;
                }
            }
            strBufHexRand.append(charArrayHexNum[index]);
        }
        return strBufHexRand.toString();
    }

    /**
     * 字符转换从UTF-8到GBK
     *
     * @param gbkStr
     * @return
     */
    public static byte[] getUTF8toGBKString(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }





    /**
     * 获取double小数点后两位 author:吴正尧
     *
     * @param dou
     * @return
     */
    public static String getTwoDouble(Double dou) {
        DecimalFormat df = new DecimalFormat("#####0.00");   //保留小数点后两位
        String d = df.format(dou);//double类型保留不到0.00位数，只能用string
        return d;
    }

    public static String getRechargeState(String status) {
        String statusReturn = "";
        switch (status) {
            case "0":
                statusReturn = "未支付";
                break;
            case "1":
                statusReturn = "支付中";
                break;
            case "2":
                statusReturn = "已支付";
                break;
            case "3":
                statusReturn = "充值中";
                break;
            case "4":
                statusReturn = "充值成功";
                break;
            default:
                break;
        }

        return statusReturn;
    }



    /**
     * 十六进制转化为十进制
     *
     * @param strHex
     * @return
     */
    public static int convertHexStr2Int(String strHex) {

        int number = Integer.parseInt(strHex, 16);

        return number;
    }

    /**
     * 电子现金以分为单位
     *
     * @param src
     * @param len
     * @param addStr
     * @return
     */
    public static String leftPad(String src, int len, String addStr) {
        if (src == null) return null;
        StringBuilder sb = new StringBuilder();
        int length = src.length();
        if (length < len) {
            int a = len - length;
            for (int i = 0; i < a; i++) {
                sb.append(addStr);
            }
        }
        sb.append(src);
        return sb.toString();
    }

    public static String totlv(String type, String sGPOdata) {
        int byteLen = sGPOdata.length() / 2;
        String byteLen16 = Integer.toHexString(byteLen);
        return type + byteLen16 + sGPOdata;
    }

    public static int strlen(String resp) {
        return resp.length() / 2;
    }

    /**
     * 分转为double 保留2位小数
     *
     * @param fen
     * @return
     */
    public static String strFenToDouble(String fen) {
        try {
            double dData = Double.parseDouble(fen) / 100;
            DecimalFormat df = new DecimalFormat("#0.00");
            String data = df.format(dData);
            return data;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 姓名、身份证号隐藏显示
     *
     * @param data
     * @param start 起始位置
     * @param len   隐藏长度
     * @return
     */
    public static String replaceChar(String data, int start, int len) {
        String dataTemp = "";
        String signTemp = "";
        if (data.length() >= (start + len)) {
            dataTemp = data.substring(start, start + len);
            for (int i = 0; i < dataTemp.length(); i++) {
                signTemp = signTemp + "*";
            }
            return data.replaceFirst(dataTemp, signTemp);
        }
        return null;
    }


    /**
     * 距离格式化
     *
     * @param distance 参数已千米为单位
     * @return
     */
    public static String formatDistance(String distance) {
        double dShopDistance = Double.parseDouble(distance);
        DecimalFormat df = new DecimalFormat("#0.0");
        String mDistance = "";
        if (dShopDistance < 1) {
            String data = df.format(dShopDistance * 1000);
            mDistance = data + "m";
        } else {
            String data = df.format(dShopDistance);
            mDistance = data + "km";
        }
        return mDistance;
    }

    public static String formatTime(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = sdf.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String dateF = sf.format(date);
            return dateF;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 对广告链接中的特殊字符
     *
     * @param href
     * @return
     */
    public static String toEscape(String href) {
        if (null != href) {
            //对广告链接中的特殊字符
            href = href.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&").replaceAll("&quot;", "\"").replaceAll("&copy;", "©");
            return href;
        }
        return null;
    }
}


